package com.niit.gateway.myfilter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author yaojianfeng
 */
@Order(-2)
@Component
public class MyParamFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        //获取auth参数
        String auth = queryParams.getFirst("auth");
        //判断是否符合要求
        if (auth != null) {
            if ("niit".equals(auth)) {

                HttpHeaders headers = exchange.getRequest().getHeaders();
                String description = headers.getFirst("Description");
                System.out.println("description : " + description);
                //放行,交给过滤器链上的其他过滤器执行
                return chain.filter(exchange);
            }
        }
        //设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //拦截请求
        return exchange.getResponse().setComplete();
    }
}
